<!-- 
	* 摘要：采购订单详情
	* 软件名称：闪酿鸿蒙版APP
	* 文件名: purchaseOrder.vue
	* 版本：1.2.0
 -->
<template>
	<view style="overflow: hidden;min-height: 100%; background-color: #f8f8f8;">
		<!-- 导航栏 -->
		<order-header class="custom-navbar" title="订单详情" 
			:status="statusInfo.status" 
			:image="statusInfo.image"
			:bt-text="statusInfo.btText" 
			@btClick="statucClick" 
			:expire="expire" 
			@back="back" 
			:isOffline="statusInfo.state == 0&&info.paymentMethod==3" 
			:orderOffline="statusInfo.state == 0&&info.paymentMethod==3"
			>
		</order-header>
		<!-- 导航栏占位盒子 -->
		<!-- #ifdef APP-PLUS -->
		<view  :style="{height:  '240rpx',marginTop:statusBarHeight+'rpx'}"></view>
		<!-- #endif -->
		<!-- #ifndef APP-PLUS -->
		<view :style="{height:  '240rpx'}"></view>
		<!-- #endif -->
		<view class="u-p-l-30 u-p-t-30 u-p-r-30" >
			<view v-if="info.state<4" class="u-p-l-35 u-p-r-35 u-p-t-28 u-p-b-28 u-font-28 u-bg-white u-theme-main" >
				<view>{{orderStatusTips(info.state,info.timeExpire)}}</view>
			</view>
			<!-- 付款单 -->
			<view class="u-m-t-20 u-flex u-col-center u-row-between box-padding box-color bottom-speac" v-if="info.tradePaymentId != null" @click="goPayDetailsFn">
				<view class="u-flex u-col-center">
					<image src="/static/order/zhifudan.png" mode="" style="width: 74rpx;height: 74rpx;"></image>
					<text class="u-font-32 u-m-l-30 u-font-bold" >付款单</text>
				</view>
				<view class="u-flex ">
					<view class="u-flex u-font-28">
						<view class="grey-color" v-if="info.paymentMethod == null">未发起支付</view>
						<view class="grey-color"  v-else>{{payMethodStatus[info.paymentMethod]}}</view>
						<text class="u-m-l-10 u-m-r-10" style="color: #999;">|</text>
						<text class=" u-font-28 u-theme-main">{{paymentStatus[info.paymentStatus]}}</text>
					</view>
					<view>
						<fui-icon name="arrowright"  style="color: #999999;" size="38"></fui-icon>
					</view>
				</view>
			</view>
			<!-- 地址 -->
			<ak-address class="u-m-t-20 u-m-b-20" :address="address"></ak-address>
			<!-- 订单信息 -->
			<ak-order-goods :info="info" @openPop="openHistory"></ak-order-goods>
			<!-- 支付信息 -->
			<ak-order-info :info="info"></ak-order-info>
			<!-- 物流信息 -->
			<ak-order-logistics v-if="info.deliveryNote" :info="info.deliveryNote"></ak-order-logistics>
		</view>
		
		
		<!-- 占位盒子 -->
		<view style="height: 160rpx;" v-if="statusInfo.state==0||statusInfo.state==2||statusInfo.state==3"></view>
		<!-- 底部固定客服 -->
		<view class="footer" v-if="statusInfo.state==0||statusInfo.state==2||statusInfo.state==3">
			<fui-button text="取消订单" class="u-m-r-20" v-if="statusInfo.state == 0" @click="modalShow = true" height="80rpx" width="200rpx" radius="45rpx" size="32" background="#F8F8F8" color="#999"></fui-button>
			<fui-button text="确认收货"  class="u-m-r-20" v-if="statusInfo.state == 2" @click="ReceiveFn"
			height="80rpx" width="200rpx" radius="45rpx" size="32" background="#FFECBF" color="#FFBB1A"></fui-button>
			<fui-button text="评价"  class="u-m-r-20" v-if="statusInfo.state == 3" @click="$mRouter.push({ route: '/pages/purchase/order/pingjia?id=' + id })"
			height="80rpx" width="200rpx" radius="45rpx" size="32" background="#FFECBF" color="#FFBB1A"></fui-button>
			<view class="u-flex" v-if="info.tradePaymentId == null&&info.tradePaymentNo == null&&info.state!==5">
				<fui-button text="立即支付"  @click="beforePayment"
				height="80rpx" width="200rpx" radius="45rpx" size="32" background="#FFECBF" color="#FFBB1A"></fui-button>
				<fui-button text="合并支付" class="u-m-l-20" @click="goCreatePayFn"
				height="80rpx" width="200rpx" radius="45rpx" size="32" background="#FFECBF" color="#FFBB1A"></fui-button>
			</view>
		</view>
		<fui-modal title="提示" :show="modalShow" :descr="modalContent" maskClosable @click="handleCancel" @cancel="modalShow = false"></fui-modal>
		<!-- <fui-actionsheet  :itemList="payList" :show="payTypeShow" @click="handlePayment"></fui-actionsheet> -->
		<u-action-sheet :list="payList" v-model="payTypeShow" @click="handlePayment">
		</u-action-sheet>
		<view v-html="alipayDom"></view>
		<fui-bottom-popup :show="useHistoryShow" @close="useHistoryShow = false;" >
			<view style="height: 800rpx;flex-direction: column;" class="u-flex">
				<view class="u-text-center u-p-t-30 u-p-b-30">参与详情</view>
				<view style="flex:1;width: 100%;">
					<z-paging ref="paging" v-model="dataList" @query="queryList" :fixed="false" :auto="true">
						<view class="u-p-t-20 u-p-b-20 u-flex"  slot="top"  style="border-top: 1px solid #EAEAEA;border-bottom: 1px solid #EAEAEA;">
							<view class="u-flex-2 u-text-center" style="color: #999;">活动</view>
							<view class="u-flex-1 u-text-center" style="color: #999;">享受次数</view>
						</view>
						<view class="promition-item u-flex" v-for="(item,index) in dataList" :key="index" >
							<view class="u-flex-2 u-text-center">
								<view class="u-font-30" style="font-weight: 500;" @click="jumpOrderFn(item.promotionId,item.promotionName)">{{item.promotionName}} <fui-icon name="arrowright" size="32"></fui-icon>  </view>
							</view>
							<view class="u-flex-1 u-text-center">
								<text v-if="item.maximumResultCount!==0&&item.maximumResultCount">{{item.resultCount+'/'+item.maximumResultCount}}</text>
								<text v-else>无限制</text>
							</view>
						</view>
					</z-paging>
				</view>
				
			</view>
		</fui-bottom-popup>
	</view>
</template>

<script>
	let systemInfo = uni.getSystemInfoSync();
	import OrderHeader from '@/components/order-header.vue'
	import AkAddress from '@/components/ak-order/address.vue'
	import AkOrderGoods from '@/components/ak-order/goods.vue'
	import AkOrderInfo from '@/components/ak-order/info.vue'
	import AkOrderLogistics from '@/components/ak-order/logistics.vue';
	import { useUserStore } from '@/store/user.js';
	import { useShopStore } from '@/store/shop.js';
	import { orderStore } from '@/store/order.js';
	import { mapState } from 'pinia';
	import utils from '@/components/firstui/fui-utils';

	export default {
		components: {
			OrderHeader,
			AkAddress,
			AkOrderGoods,
			AkOrderInfo,
			AkOrderLogistics
		},
		data() {
			return {
				id: null,
				alipayDom: '',
				modalShow: false,
				modalContent: '是否确认取消订单',
				info: {},
				address: {},
				invoice: {},
				state: 0,
				statusInfo: {},
				boxHeight: 0,
				payTypeShow: false,
				paymentMethod: null,
				expire: '',
				expireTimer: undefined,
				isGoPay:false,
				loading:false,
				payList:[],
				offlineSet:{},
				tradePaymentId:'',
				paymentStatus:['待付款','待到账','已完成','部分完成','支付失败','已关闭','退款中','已退款',],
				tradePaymentNo:'',
				statusBarHeight: systemInfo.statusBarHeight,
				useHistoryShow:false,
				dataList:[],
				joinedActivity:'',
				payMethodStatus:['微信支付','支付宝支付','银联支付','线下支付','线下支付'],
			}
		},
		computed:{
			...mapState(useUserStore,['isPurchase','isReceive','isPayment']),
			...mapState(orderStore,['orderStatus']),
			...mapState(useShopStore, {
				storeShop: 'shop',
			})	
		},
		async onLoad(options) {
			this.id = options.id;
			this.joinedActivity = options.activityId
			if(options.paymentMethod!==undefined){
				this.handlePayment('jiesuan',options.paymentMethod)
			}
			// await this.getOrderDetail()
			// if (this.info.state == 0) {
			// 	this.timeExpire()
			// }
		},
		onHide() {
			clearInterval(this.expireTimer)
		},
		onUnload() {
			clearInterval(this.expireTimer)
		},
		onShow() {
			if(this.isGoPay){
				this.$mRouter.redirectTo({
					route: '/pages/purchase/payorder/payresult?id=' + this.id
				})
			}
			this.getOrderDetail();
		},
		methods: {
			openHistory(){
				this.useHistoryShow = true;
			},
			jumpOrderFn(id,name){
				if(this.joinedActivity === id){
					this.back();
				}else{
					this.$mRouter.push({ route: '/pages/index/huodong?id=' + id + '&name=' + name })
				}
			},
			// 活动参与列表
			async queryList(pageNo, pageSize) {
				//组件加载时会自动触发此方法，因此默认页面加载时会自动触发，无需手动调用
				//这里的pageNo和pageSize会自动计算好，直接传给服务器即可
				//模拟请求服务器获取分页数据，请替换成自己的网络请求
				const params = {
					pageIndex: pageNo,
					pageSize: pageSize,
					BuyerId:this.storeShop.id,
					// IsSeller:true
					tradeId:this.id
				}
				const res = await this.$newHttp.get('api/v1.2/SalesPromotion/GetTradeUsePromotionsPage', { params: params } );
				if(res.code === 200){
					this.$refs.paging.complete(res.data.list);
				}else{
					this.$refs.paging.complete(false);
				}
			},
			
			// 订单关闭倒计时显示文字
			 orderStatusTips(type, timeExpire) {
			      let nowTime = new Date();
			      let endTime = new Date(timeExpire);
			      var leftTime = endTime.getTime() - nowTime.getTime();
			      let isExpire = leftTime < 0 ? false : true;
			      let text = '';
			      let initTime = utils.dateFormatter(timeExpire, 'y年m月d日 h时i分');
			      switch (type) {
			        case 0:
			          if (this.info.settlementMethod === 1) {
			            text = '待确认，先货后款：若销售商未在【' + initTime+ '】前确认本订单，系统将自动取消本订单';
			          } else {
			            text = '待确认，先款后货：请您在【' +initTime+ '】前发起付款，若未发起付款，系统将自动取消本订单';
			          }
			          return isExpire ? text : '系统即将自动取消本订单';
			          break;
			        case 1:
			          return '请耐心等待，销售商正在备货';
			          break;
			        case 2:
			          text = '系统将在【' +initTime+ '】后自动收货';
			          return isExpire ? text : '系统即将自动收货';
			          break;
			        case 3:
			          text = '系统将在【' +initTime+ '】后自动完成订单';
			          return isExpire ? text : '系统即将自动完成订单';
			          break;
			        default: return '';
			      }
			    },
			// 倒计时
			timeExpire() {
				this.expireTimer = setInterval(() => {
					let nowTime = new Date();
					let orderTime = new Date(this.info.timeExpire.replace(new RegExp('-', 'g'), '/'));
					let leftTime = orderTime.getTime() - nowTime.getTime();

					if (leftTime < 0) {
						this.expire = ''
						clearInterval(this.expireTimer)
					} else {
						let leftSecond = parseInt(leftTime / 1000);
						let Day = Math.floor(leftSecond / (60 * 60 * 24));
						let Hour = Math.floor((leftSecond - Day * 24 * 60 * 60) / 3600);
						let Minute = Math.floor((leftSecond - Day * 24 * 60 * 60 - Hour * 3600) / 60);
						let Second = Math.floor(leftSecond - Day * 24 * 60 * 60 - Hour * 3600 - Minute * 60);
						let HourShow = Hour?this.formatTen(Hour) + "小时":'';
						let MinuteShow = Minute?this.formatTen(Minute) + "分":'';
						this.expire = HourShow + MinuteShow + this.formatTen(Second) + '秒';
					}
				}, 1000)
			},
			formatTen(num) {
				return num > 9 ? (num + "") : ("0" + num);
			},
			// 获取商品详情
			async getOrderDetail() {
				const res = await this.$http.get('api/Trade/GetPurchaseTradeDetail', {
					params: {
						id: this.id
					}
				})
				
				this.info = res;
				// if (this.info.state == 0) {
				// 	this.timeExpire();
				// }
				this.address = res.deliveryAddress
				this.invoice = res.shopInvoiceConfig
				this.statusInfo = this.orderStatus.find(item => {
					return item.state == res.state // 待付款
				})
				this.tradePaymentId = res.tradePaymentId;
				this.tradePaymentNo = res.tradePaymentNo;
			},
			// 支付前判断
			async beforePayment() {
				if (!this.isPayment) {
					return this.$u.toast('您没有付款权限，请联系有付款权限的同事付款')
				}else{
					try{
					
						let res = await this.$http.get('api/Trade/GetContract',{ params: {
							buyerId: this.storeShop.id,
							sellerId:this.info.sellerShopId
						}});
						console.log(res);
						this.loading = false
						let payList = [];
						let offlineNo = 1;
						if(res.shopCollections.length!=0){
							res.shopCollections.forEach(item=>{
								if(item.shopCollectionType === 5){
									payList.push(
										{
											value: 0,
											text: '微信支付'
										})
								}
								if(item.shopCollectionType === 1){
									payList.push(
										{
											value: 11,
											text: '支付宝支付'
										})
								}
								if(item.shopCollectionType === 3){
									payList.push(
										{
											value: 3,
											text: '线下支付'+(offlineNo>1?offlineNo:''),
											bankOfDeposit:item.bankOfDeposit,
											accountNumber:item.accountNumber,
											accountName:item.accountName,
										})
										offlineNo++;
								}
								if(item.shopCollectionType === 4){
									payList.push(
										{
											value: 4,
											text: '线下支付(月结)',
											bankOfDeposit:item.bankOfDeposit,
											accountNumber:item.accountNumber,
											accountName:item.accountName,
										})
								}
							});
							this.payList = payList;
							this.payTypeShow = true
						}else{
							this.$refs.uToast.show({
								title: this.info.sellerShopName+'没有设置相关的收款方式，请联系客服处理',
								type: 'error',
								icon:false,
								position:'bottom'
							})
						}
					}catch(e){
						//TODO handle the exception
						this.loading = false
						this.$refs.uToast.show({
							title: e,
							type: 'error',
							position:'bottom'
						})
					}
				}
			},
			async handleCancel(e) {
				if(e.index === 0){
					this.modalShow = false;
					return false;
				}else{
					// 0 待付款 2 确认收货
					if (this.info.state == 0) {
						if(!this.isPurchase){
							return this.$u.toast('当前账号没有取消订单的权限')
						}else{
							const res = await this.$http.put('api/Trade/BuyerCancellationTrade?id=' + this.id)
							this.$u.toast('取消成功', 1000, 'success')
							this.$mHelper.delayedJump()
						}
					} else if (this.info.state == 2) { 
						if(!this.isReceive){
							return this.$u.toast('当前账号没有确认收货的权限')
						}else{
							const res = await this.$http.put('api/Trade/ConfirmReceipt?id=' + this.id)
							this.$u.toast('已收货', 1000, 'success')
							this.$mHelper.delayedJump('/pages/purchase/order/pingjia?id=' + this.id, 'redirectTo')
						}
					}
					this.modalShow = false;
				}
					
				// this.$mHelper.delayedJump('/pages/purchase/order/index', 'redirectTo')
			},
			// 支付订单
			async handlePayment(index,paymentMethod) {
				if(!this.isPayment){
					return this.$u.toast('当前账号没有付款的权限，请联系管理员处理~');
				}
				console.log(index);
				if(index === 'jiesuan'){
					this.paymentMethod = paymentMethod;
				}else{
					this.paymentMethod = this.payList[index].value;
				}
				if(this.tradePaymentId == null||this.tradePaymentId == ''){
					let result = await this.createPayorderFn();
					if(!result) return false;
				}
				// 微信app支付
				if (this.paymentMethod == 0) {
					// #ifdef  H5
					uni.showToast({
						title: '未开放H5微信支付'
					})
					// #endif
					// #ifdef APP-PLUS
					let res = await this.$http.post('api/TradePayment/Pay', {
						id: this.tradePaymentId,
						paymentMethod: 0
					});
					let that = this;
					let orderInfo = JSON.parse(res);
					uni.requestPayment({
						"provider": "wxpay",
						"orderInfo": JSON.parse(res),
						success: function(res) {
							that.$mRouter.redirectTo({
								route: '/pages/purchase/payorder/payresult?id=' + that.tradePaymentId
							})
						},
						fail: function(err) {
							that.$mRouter.redirectTo({
								route: '/pages/purchase/payorder/payresult?id=' + that.tradePaymentId
							})
						}
					});
					// #endif
				}
				// 支付宝app支付
				if (this.paymentMethod == 1) {
					// #ifdef  H5
					let res = await this.$http.post('api/TradePayment/Pay', {
						id: this.tradePaymentId,
						paymentMethod: 5
					});
					this.alipayDom = res;
					setTimeout(function() {
						document.forms['alipaysubmit'].submit();
					}, 500)
					// #endif
					// #ifdef APP-PLUS
					let res = await this.$http.post('api/TradePayment/Pay', {
						id: this.tradePaymentId,
						paymentMethod: 6
					});
					let orderInfo = res;
					let that = this;
					uni.requestPayment({
						"provider": "alipay", //固定值为"alipay"
						"orderInfo": orderInfo, //此处为服务器返回的订单信息字符串
						success: function(res) {
							console.log("支付成功");
							that.$mRouter.redirectTo({
								route: '/pages/purchase/payorder/payresult?id=' + that.tradePaymentId
							})
						},
						fail: function(err) {
							console.log('支付失败:' + JSON.stringify(err));
							that.$mRouter.redirectTo({
								route: '/pages/purchase/payorder/payresult?id=' + that.tradePaymentId
							})
						}
					});
					// #endif
				}
				// 线下支付
				if (this.paymentMethod == 3 || this.paymentMethod == 4) {
					this.offlineSet.id = this.tradePaymentId;
					this.offlineSet.sellerName = this.info.sellerShopName;
					this.offlineSet.paymentNo = this.tradePaymentNo;
					this.offlineSet.actualAmount = this.info.actualAmount;
					this.offlineSet.paymentMethod = this.paymentMethod;
					this.offlineSet.bankOfDeposit = this.payList[index].bankOfDeposit;
					this.offlineSet.accountNumber = this.payList[index].accountNumber;
					this.offlineSet.accountName = this.payList[index].accountName;
					this.$mRouter.push({
						route: '/pages/cart/offline?offlineSet=' + JSON.stringify(this.offlineSet)
					})
				}
				// 支付宝当面付
				if (this.paymentMethod == 11) {
					let res = await this.$http.post('api/TradePayment/Pay', {
						id: this.tradePaymentId,
						paymentMethod: 11
					});
					console.log(res);
					let device = uni.getSystemInfoSync().platform;
					if (device === 'ios') {
						this.isGoPay = true;
						plus.runtime.openURL('alipay://platformapi/startapp?appId=20000067&url=' + encodeURIComponent(
							res))
					} else {
						this.isGoPay = true;
						plus.runtime.openURL('alipays://platformapi/startapp?appId=20000067&url=' + encodeURIComponent(
							res))
					}
				}
			},
			statucClick() {
				// 3 评价
				if (this.statusInfo.state == 3) {
					this.$mRouter.push({
						route: '/pages/purchase/order/pingjia?id=' + this.id
					})
				}
			},
			async createPayorderFn(){
				this.loading = true;
				let payorderParams = {
					tradeIds:[this.info.id],
					isSeller:false,
					shopId:this.storeShop.id,
				}
				const payorderRes =  await this.$newHttp.post('api/TradePayment/Create', payorderParams);
				this.loading = false;
				if(payorderRes.code == 200){
					this.tradePaymentId = payorderRes.data.id;
					this.tradePaymentNo = payorderRes.data.paymentNo;
					return true;
				}else{
					uni.showToast({
						title:'创建付款单失败，错误信息：'+payorderRes.erroMessage
					})
					return false;
				} 
				
			},
			back() {
				clearInterval(this.expireTimer)
				let pages = getCurrentPages(); // 当前页面
				let beforePage = pages[pages.length - 2]; // 上一页
				console.log(beforePage); 
				if(beforePage){
					if(beforePage.route === 'pages/public/xiaoxi/messageDeatails'||beforePage.route === 'pages/shangpin/huodong'||beforePage.route === 'pages/purchase/zhanghu/tradeDetails'){
						uni.navigateBack();
					}else{
						this.$mRouter.redirectTo({
							route: '/pages/purchase/order/index'
						})
					}
				}else{
					this.$mRouter.redirectTo({
						route: '/pages/purchase/order/index'
					})
				}
				
				
			},
			// 确认收款
			ReceiveFn(){
				this.modalContent = '是否确认收货'
				this.modalShow = true;
			},
			goPayDetailsFn(){
				if(!(this.isPurchase||this.isPayment)){
					return this.$u.toast('当前账号没有查看付款单的权限，请联系管理员处理~');
				}
				this.$mRouter.push({
					route: '/pages/purchase/payorder/details?id='+this.tradePaymentId+'&routeFrom=order&orderId='+this.info.id
				})
			},
			goCreatePayFn(){
				if (!this.isPayment) {
					return this.$u.toast('您没有付款权限，请联系有付款权限的同事付款')
				}else{
					this.$mRouter.push({
						route: '/pages/purchase/payorder/createPayOrder?shop='+this.info.sellerShopId+'&routeFrom=order&orderId='+this.info.id
					})
				}
				
			}
			
		}
	}
</script>

<style lang="scss" scoped>
	.yx-bt {
		width: 200rpx;
		height: 80rpx;
		border: 2rpx solid $uni-text-color;
		border-radius: 40px;
		text-align: center;
		line-height: 80rpx;
		font-size: 28rpx;
	}
	.paryorder-mark{
		width: 5rpx;
		height: 16rpx;
		background: #FF551A;
		border-radius: 3rpx;
		margin-right: 14rpx;
	}
	.promition-item{
		box-sizing: border-box;
		padding: 28rpx 0rpx;
		background-color: #F8F8F8;
		border-bottom: 1px solid #eaeaea;
	}
	.footer {
		height: 140rpx;
		width: 100%;
		position: fixed;
		bottom: 0;
		background-color: #FFFFFF;
		display: flex;
		justify-content: flex-end;
		align-items: center;
		padding: 30rpx 35rpx;
		z-index: 9;
		border-top: 1rpx solid #EEEEEE;
	}
</style>
